﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;

namespace LprMiddleWare.Views
{
    /// <summary>
    /// Interaction logic for ProgressWindow.xaml
    /// </summary>
    public partial class ProgressWindow : Window, INotifyPropertyChanged
    {
        private int _retryCount = 1;
        private IDisposable _ob;

        public int RetryCount
        {
            get { return _retryCount; }
            set
            {
                _retryCount = value;
                RaisePropertyChanged("RetryCount");
            }
        }

        public ProgressWindow()
        {
            this.DataContext = this;
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var timer = Observable.Interval(TimeSpan.FromSeconds(3));
            _ob = timer.ObserveOn(SynchronizationContext.Current).Subscribe(ConnectToDB);
        }

        private void ConnectToDB(long l)
        {
            try
            {
                RetryCount += 1;
                InitDB();
                CloseWindow();
            }
            catch
            {
                if (RetryCount >= 10)
                {
                    CloseWindow();
                    Settings.LoadDefault().Save2Db = false;
                    MessageBox.Show("无法连接数据库，车牌保存到数据库已经被关闭，请检查数据库配置");
                }
            }
        }

        private void CloseWindow()
        {
            _ob.Dispose();
            this.Close();
        }

        private static void InitDB()
        {
            var settings = Settings.LoadDefault();
            settings.Validate();
            if (!settings.HasErrors)
            {
                var dataLayer = Helper.ConnectToOracleDb(settings.DbServer, settings.DbUserName, settings.DbPassWord);
                XpoDefault.DataLayer = dataLayer;
            }
        }

       


        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
